<?php

namespace App\Repositories;

use Carbon\Carbon;
use App\Exceptions\BasicException;
use Illuminate\Support\Facades\DB;

use function Clue\StreamFilter\fun;

class WarOrderRepository
{
    public function getSeasonList($where = [], $page = 1, $perPage = 15)
    {
        return app('model_war_order')
            ->select(['id', 'name', 'time_from', 'time_to', 'advance_price'])
            ->orderBy('id', 'desc')
            ->where($where)
            ->paginate($perPage, ['*'], '', $page);
    }

    public function addSeason($params)
    {
        $name = $params['name'];
        $id = $params['id'] ?? 0;
        if ($id > 0) {
            if (app('model_war_order')->where('id', '<>', $id)->where('name', $name)->count() > 0) {
                throw new BasicException(0, '名称已存在');
            }
            app('model_war_order')->where('id', $id)->update([
                'name'          => $name,
                'time_from'     => strtotime($params['time_from']),
                'time_to'       => strtotime($params['time_to']),
                'advance_price' => $params['advance_price'],
            ]);
        } else {
            if (app('model_war_order')->where('name', $name)->count() > 0) {
                throw new BasicException(0, '名称已存在');
            }
            app('model_war_order')->insert([
                'name'          => $name,
                'time_from'     => strtotime($params['time_from']),
                'time_to'       => strtotime($params['time_to']),
                'advance_price' => $params['advance_price'],
                'add_time'      => Carbon::now()->timestamp,
            ]);
        }
    }

    //战令详情
    public function getWarOrderDetail($war_order_id)
    {
        $war_order_levels = app('model_war_order_detail')->where([
            'war_order_id' => $war_order_id,
            'status'       => 1,
        ])->orderBy('level', 'asc')->orderBy('id', 'asc')->get();
        $war_order_rewards = app('model_war_order_reward')->where(['war_order_id' => $war_order_id])->get();
        $reward_data = [];

        foreach ($war_order_rewards as $key => $value) {
            $reward = app('repo_reward')->getRewardDetail($value->reward_id, $value->reward_type, $value->number);
            $data = [
                'id'      => $value->id,
                'item_id' => $reward['id'],
                'name'    => $reward['name'],
                'picture' => $reward['picture'],
                'number'  => $reward['number'],
            ];
            if ($value->type == 1) {
                $reward_data[$value->detail_id]['normal'][] = $data;
            } else {
                $reward_data[$value->detail_id]['special'][] = $data;
            }
        }

        $level_list = [];
        foreach ($war_order_levels as $key => $level) {
            $level_list[] = [
                'id'           => $level->id,
                'war_order_id' => $level->war_order_id,
                'level'        => $level->level,
                'price'        => $level->price,
                'experience'   => $level->experience,
                'normal'       => $reward_data[$level->id]['normal'] ?? [],
                'special'      => $reward_data[$level->id]['special'] ?? [],
            ];
        }

        return $level_list;
    }

    //赛季宣传礼物列表
    public function getRewardList($where = [])
    {
        $war_order_rewards = app('model_war_order_reward')->where($where)->get();
        $reward_data = [];

        foreach ($war_order_rewards as $key => $value) {
            $reward = app('repo_reward')->getRewardDetail($value->reward_id, $value->reward_type, $value->number);
            $reward_data[] = [
                'id'           => $value->id,
                'detail_id'    => $value->detail_id,
                'war_order_id' => $value->war_order_id,
                'item_id'      => $reward['id'],
                'name'         => $reward['name'],
                'picture'      => $reward['picture'],
                'number'       => $reward['number'],
                'type'         => $value->type,
                'recommend'    => $value->recommend == 1 ? 1 : 0,
            ];
        }

        return $reward_data;
    }

    public function addWarOrder($params)
    {
        $data = [
            'war_order_id' => $params['war_order_id'],
            'level'        => $params['level'],
            'experience'   => $params['experience'],
            'price'        => $params['price'],
        ];
        $id = $params['id'] ?? 0;
        $rewards = $params['rewards'] ?? [];
        $rewards = json_decode($rewards, true);

        $where_level = [
            ['war_order_id', $params['war_order_id']],
            ['level', $params['level']],
        ];
        if ($id > 0) {
            $where_level[] = ['id', '<>', $id];
        }
        if (app('model_war_order_detail')->where($where_level)->count() > 0) {
            throw new BasicException(0, '等级已存在');
        }

        DB::beginTransaction();
        try {
            if ($id > 0) {
                app('model_war_order_detail')->where('id', $id)->update($data);
            } else {
                $data['add_time'] = Carbon::now()->timestamp;
                $id = app('model_war_order_detail')->insertGetId($data);
                if (!$id) {
                    throw new BasicException(0, '添加失败');
                }
            }
            app('model_war_order_reward')->where('detail_id', $id)->delete();
            $insert_reward = [];
            foreach ($rewards as $reward) {
                $type = $reward['type'] ?? -1;
                if (!in_array($type, [1, 2, 3])) {
                    continue;
                }
                $insert_reward[] = [
                    'war_order_id' => $params['war_order_id'],
                    'detail_id'    => $id,
                    'type'         => $type,
                    'reward_id'    => $reward['reward_id'],
                    'number'       => $reward['number'],
                    'reward_type'  => 2,
                ];
            }
            if ($insert_reward) {
                app('model_war_order_reward')->insert($insert_reward);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, '操作失败');
        }
    }
    //导入上期战令
    public function importWarOrder($war_order_id)
    {
        $war_order = app('model_war_order')->where('id', $war_order_id)->first();
        if (!$war_order) {
            throw new BasicException(0, '赛季不存在, 请重新选择赛季');
        }
        $war_order_detail = app('model_war_order_detail')->where('war_order_id', $war_order_id)->first();
        if ($war_order_detail) {
            throw new BasicException(0, '请先删除当前数据后再一键导入');
        }

        //获取上期战令信息
        $war_order_last = app('model_war_order')->where('id', '<', $war_order_id)->orderBy('id', 'desc')->first();
        if (!$war_order_last) {
            throw new BasicException(0, '上期赛季不存在, 无法导入');
        }
        $war_order_detail_last = app('model_war_order_detail')->where('war_order_id', $war_order_last->id)->orderBy('level', 'asc')->get()->toArray();
        if (empty($war_order_detail_last)) {
            throw new BasicException(0, '上期赛季无战令, 无法导入');
        }
        $war_order_reward_last = app('model_war_order_reward')->where('war_order_id', $war_order_last->id)->get()->toArray();
        $war_order_reward_last_format = [];
        foreach ($war_order_reward_last as $reward) {
            $war_order_reward_last_format[$reward['detail_id']][] = $reward;
        }

        $now_time = Carbon::now()->timestamp;
        DB::beginTransaction();
        try {
            foreach($war_order_detail_last as $value) {
                $ori_detail_id = $value['id'];
                $value['war_order_id'] = $war_order_id;
                $value['add_time'] = $now_time;
                unset($value['id']);
                $detail_id = app('model_war_order_detail')->insertGetId($value);
                if (isset($war_order_reward_last_format[$ori_detail_id])) {
                    $reward_data = $war_order_reward_last_format[$ori_detail_id];
                    $reward_data = array_map(function($v) use ($detail_id, $war_order_id) {
                        $v['war_order_id'] = $war_order_id;
                        $v['detail_id'] = $detail_id;
                        unset($v['id']);
                        return $v;
                    }, $reward_data);
                    app('model_war_order_reward')->insert($reward_data);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, '操作失败');
        }
    }

    public function updateRecommend($params)
    {
        $where['detail_id'] = $params['detail_id'];
        $where['id'] = $params['id'];

        app('model_war_order_reward')->where($where)->update(['recommend' => $params['recommend']]);
    }

    public function getUpgradeList($request)
    {
        $user_code = $request->input('user_code');
        $season_name = $request->input('season_name');
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 15);
        $where = [];
        $where_user = $where_war_order = [];
        if ($user_code) {
            $where_user['user_code'] = $user_code;
        }
        if ($season_name) {
            $where_war_order[] = ['name', 'like', "%$season_name%"];
        }

        $result = app('model_war_order_user_level')
            ->with('user_data:user_id,user_code,nickname,sex,head_picture')
            ->with('war_order:id,name')
            ->select(['id', 'user_id', 'war_order_id', 'level_from', 'level_to', 'cost_gold', 'type', 'add_time'])
            ->orderBy('id', 'desc')
            ->where($where)
            ->whereHas('user_data', function ($query) use ($where_user) {
                $query->where($where_user);
            })
            ->whereHas('war_order', function ($query) use ($where_war_order) {
                $query->where($where_war_order);
            })
            ->paginate($perPage, ['*'], '', $page);

        return $result;
    }

    public function getOrderList($request)
    {
        $user_code = $request->input('user_code');
        $season_name = $request->input('season_name');
        $page = $request->input('page', 1);
        $perPage = $request->input('perPage', 15);
        $where = [];
        $where_user = $where_war_order = [];
        if ($user_code) {
            $where_user['user_code'] = $user_code;
        }
        if ($season_name) {
            $where_war_order[] = ['name', 'like', "%$season_name%"];
        }

        $result = app('model_war_order_user_advanced')
            ->with('user_data:user_id,user_code,nickname,sex,head_picture')
            ->with('war_order:id,name')
            ->select(['id', 'user_id', 'war_order_id', 'cost_gold', 'add_time'])
            ->orderBy('id', 'desc')
            ->where($where)
            ->whereHas('user_data', function ($query) use ($where_user) {
                $query->where($where_user);
            })
            ->whereHas('war_order', function ($query) use ($where_war_order) {
                $query->where($where_war_order);
            })
            ->paginate($perPage, ['*'], '', $page);

        return $result;
    }
}
